acme.sh 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  1. #!/usr/bin/env bash
  2. VER=2.2.1
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  7. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  8. DEFAULT_USER_AGENT="$PROJECT_ENTRY client: $PROJECT"
  9. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  10. VTYPE_HTTP="http-01"
  11. VTYPE_DNS="dns-01"
  12. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  13. END_CSR="-----END CERTIFICATE REQUEST-----"
  14. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  15. END_CERT="-----END CERTIFICATE-----"
  16. if [ -z "$AGREEMENT" ] ; then
  17. AGREEMENT="$DEFAULT_AGREEMENT"
  18. fi
  19. _URGLY_PRINTF=""
  20. if [ "$(printf '\x41')" != 'A' ] ; then
  21. _URGLY_PRINTF=1
  22. fi
  23. _info() {
  24. if [ -z "$2" ] ; then
  25. echo "[$(date)] $1"
  26. else
  27. echo "[$(date)] $1"="'$2'"
  28. fi
  29. }
  30. _err() {
  31. _info "$@" >&2
  32. return 1
  33. }
  34. _debug() {
  35. if [ -z "$DEBUG" ] ; then
  36. return
  37. fi
  38. _err "$@"
  39. return 0
  40. }
  41. _debug2() {
  42. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  43. _debug "$@"
  44. fi
  45. return
  46. }
  47. _startswith(){
  48. _str="$1"
  49. _sub="$2"
  50. echo $_str | grep ^$_sub >/dev/null 2>&1
  51. }
  52. _contains(){
  53. _str="$1"
  54. _sub="$2"
  55. echo $_str | grep $_sub >/dev/null 2>&1
  56. }
  57. _exists(){
  58. cmd="$1"
  59. if [ -z "$cmd" ] ; then
  60. _err "Usage: _exists cmd"
  61. return 1
  62. fi
  63. if type command >/dev/null 2>&1 ; then
  64. command -v $cmd >/dev/null 2>&1
  65. else
  66. type $cmd >/dev/null 2>&1
  67. fi
  68. ret="$?"
  69. _debug2 "$cmd exists=$ret"
  70. return $ret
  71. }
  72. #a + b
  73. _math(){
  74. expr "$@"
  75. }
  76. _h_char_2_dec() {
  77. _ch=$1
  78. case "${_ch}" in
  79. a|A)
  80. echo -n 10
  81. ;;
  82. b|B)
  83. echo -n 11
  84. ;;
  85. c|C)
  86. echo -n 12
  87. ;;
  88. d|D)
  89. echo -n 13
  90. ;;
  91. e|E)
  92. echo -n 14
  93. ;;
  94. f|F)
  95. echo -n 15
  96. ;;
  97. *)
  98. echo -n $_ch
  99. ;;
  100. esac
  101. }
  102. _h2b() {
  103. hex=$(cat)
  104. i=1
  105. j=2
  106. if _exists let ; then
  107. uselet="1"
  108. fi
  109. _debug uselet "$uselet"
  110. _debug _URGLY_PRINTF "$_URGLY_PRINTF"
  111. while [ '1' ] ; do
  112. if [ -z "$_URGLY_PRINTF" ] ; then
  113. h=$(printf $hex | cut -c $i-$j)
  114. if [ -z "$h" ] ; then
  115. break;
  116. fi
  117. printf "\x$h"
  118. else
  119. ic=$(printf $hex | cut -c $i)
  120. jc=$(printf $hex | cut -c $j)
  121. if [ -z "$ic$jc" ] ; then
  122. break;
  123. fi
  124. ic="$(_h_char_2_dec $ic)"
  125. jc="$(_h_char_2_dec $jc)"
  126. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  127. fi
  128. if [ "$uselet" ] ; then
  129. let "i+=2" >/dev/null
  130. let "j+=2" >/dev/null
  131. else
  132. i="$(_math $i + 2)"
  133. j="$(_math $j + 2)"
  134. fi
  135. done
  136. }
  137. #options file
  138. _sed_i() {
  139. options="$1"
  140. filename="$2"
  141. if [ -z "$filename" ] ; then
  142. _err "Usage:_sed_i options filename"
  143. return 1
  144. fi
  145. if sed -h 2>&1 | grep "\-i[SUFFIX]" ; then
  146. _debug "Using sed -i"
  147. sed -i ""
  148. else
  149. _debug "No -i support in sed"
  150. text="$(cat $filename)"
  151. echo "$text" | sed "$options" > "$filename"
  152. fi
  153. }
  154. #Usage: file startline endline
  155. _getfile() {
  156. filename="$1"
  157. startline="$2"
  158. endline="$3"
  159. if [ -z "$endline" ] ; then
  160. _err "Usage: file startline endline"
  161. return 1
  162. fi
  163. i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
  164. if [ -z "$i" ] ; then
  165. _err "Can not find start line: $startline"
  166. return 1
  167. fi
  168. _debug i $i
  169. j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
  170. if [ -z "$j" ] ; then
  171. _err "Can not find end line: $endline"
  172. return 1
  173. fi
  174. _debug j $j
  175. sed -n $i,${j}p "$filename" | head -n -1 | tail -n +2
  176. }
  177. #Usage: multiline
  178. _base64() {
  179. if [ "$1" ] ; then
  180. openssl base64 -e
  181. else
  182. openssl base64 -e | tr -d '\r\n'
  183. fi
  184. }
  185. #Usage: multiline
  186. _dbase64() {
  187. if [ "$1" ] ; then
  188. openssl base64 -d -A
  189. else
  190. openssl base64 -d
  191. fi
  192. }
  193. #Usage: hashalg
  194. #Output Base64-encoded digest
  195. _digest() {
  196. alg="$1"
  197. if [ -z "$alg" ] ; then
  198. _err "Usage: _digest hashalg"
  199. return 1
  200. fi
  201. if [ "$alg" = "sha256" ] ; then
  202. openssl dgst -sha256 -binary | _base64
  203. else
  204. _err "$alg is not supported yet"
  205. return 1
  206. fi
  207. }
  208. #Usage: keyfile hashalg
  209. #Output: Base64-encoded signature value
  210. _sign() {
  211. keyfile="$1"
  212. alg="$2"
  213. if [ -z "$alg" ] ; then
  214. _err "Usage: _sign keyfile hashalg"
  215. return 1
  216. fi
  217. if [ "$alg" = "sha256" ] ; then
  218. openssl dgst -sha256 -sign "$keyfile" | _base64
  219. else
  220. _err "$alg is not supported yet"
  221. return 1
  222. fi
  223. }
  224. _ss() {
  225. _port="$1"
  226. if _exists "ss" ; then
  227. _debug "Using: ss"
  228. ss -ntpl | grep :$_port" "
  229. return 0
  230. fi
  231. if _exists "netstat" ; then
  232. _debug "Using: netstat"
  233. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  234. #for windows version netstat tool
  235. netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
  236. else
  237. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  238. netstat -an -p tcp | grep LISTEN | grep :$_port" "
  239. else
  240. netstat -ntpl | grep :$_port" "
  241. fi
  242. fi
  243. return 0
  244. fi
  245. return 1
  246. }
  247. toPkcs() {
  248. domain="$1"
  249. pfxPassword="$2"
  250. if [ -z "$domain" ] ; then
  251. echo "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  252. return 1
  253. fi
  254. _initpath "$domain"
  255. if [ "$pfxPassword" ] ; then
  256. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  257. else
  258. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  259. fi
  260. if [ "$?" = "0" ] ; then
  261. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  262. fi
  263. }
  264. #domain [2048]
  265. createAccountKey() {
  266. _info "Creating account key"
  267. if [ -z "$1" ] ; then
  268. echo Usage: $PROJECT_ENTRY --createAccountKey -d domain.com [--accountkeylength 2048]
  269. return
  270. fi
  271. account=$1
  272. length=$2
  273. _debug account "$account"
  274. _debug length "$length"
  275. if _startswith "$length" "ec-" ; then
  276. length=2048
  277. fi
  278. if [ -z "$2" ] || [ "$2" = "no" ] ; then
  279. _info "Use default length 2048"
  280. length=2048
  281. fi
  282. _initpath
  283. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  284. _info "Account key exists, skip"
  285. return
  286. else
  287. #generate account key
  288. openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
  289. fi
  290. }
  291. #domain length
  292. createDomainKey() {
  293. _info "Creating domain key"
  294. if [ -z "$1" ] ; then
  295. echo Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]
  296. return
  297. fi
  298. domain=$1
  299. length=$2
  300. isec=""
  301. if _startswith "$length" "ec-" ; then
  302. isec="1"
  303. length=$(printf $length | cut -d '-' -f 2-100)
  304. eccname="$length"
  305. fi
  306. if [ -z "$length" ] ; then
  307. if [ "$isec" ] ; then
  308. length=256
  309. else
  310. length=2048
  311. fi
  312. fi
  313. _info "Use length $length"
  314. if [ "$isec" ] ; then
  315. if [ "$length" = "256" ] ; then
  316. eccname="prime256v1"
  317. fi
  318. if [ "$length" = "384" ] ; then
  319. eccname="secp384r1"
  320. fi
  321. if [ "$length" = "521" ] ; then
  322. eccname="secp521r1"
  323. fi
  324. _info "Using ec name: $eccname"
  325. fi
  326. _initpath $domain
  327. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  328. #generate account key
  329. if [ "$isec" ] ; then
  330. openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
  331. else
  332. openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
  333. fi
  334. else
  335. if [ "$IS_RENEW" ] ; then
  336. _info "Domain key exists, skip"
  337. return 0
  338. else
  339. _err "Domain key exists, do you want to overwrite the key?"
  340. _err "Add '--force', and try again."
  341. return 1
  342. fi
  343. fi
  344. }
  345. # domain domainlist
  346. createCSR() {
  347. _info "Creating csr"
  348. if [ -z "$1" ] ; then
  349. echo Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]
  350. return
  351. fi
  352. domain=$1
  353. _initpath $domain
  354. domainlist=$2
  355. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  356. _info "CSR exists, skip"
  357. return
  358. fi
  359. if [ -z "$domainlist" ] || [ "$domainlist" = "no" ]; then
  360. #single domain
  361. _info "Single domain" $domain
  362. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
  363. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  364. else
  365. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  366. #multi
  367. _info "Multi domain" "$alt"
  368. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
  369. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  370. fi
  371. }
  372. _urlencode() {
  373. __n=$(cat)
  374. echo $__n | tr '/+' '_-' | tr -d '= '
  375. }
  376. _time2str() {
  377. #BSD
  378. if date -u -d@$1 2>/dev/null ; then
  379. return
  380. fi
  381. #Linux
  382. if date -u -r $1 2>/dev/null ; then
  383. return
  384. fi
  385. }
  386. _stat() {
  387. #Linux
  388. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  389. return
  390. fi
  391. #BSD
  392. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  393. return
  394. fi
  395. }
  396. #keyfile
  397. _calcjwk() {
  398. keyfile="$1"
  399. if [ -z "$keyfile" ] ; then
  400. _err "Usage: _calcjwk keyfile"
  401. return 1
  402. fi
  403. EC_SIGN=""
  404. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  405. _debug "RSA key"
  406. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  407. if [ "${#pub_exp}" = "5" ] ; then
  408. pub_exp=0$pub_exp
  409. fi
  410. _debug2 pub_exp "$pub_exp"
  411. e=$(echo $pub_exp | _h2b | _base64)
  412. _debug2 e "$e"
  413. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  414. _debug2 modulus "$modulus"
  415. n=$(echo -n $modulus| _h2b | _base64 | _urlencode )
  416. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  417. _debug2 jwk "$jwk"
  418. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  419. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  420. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  421. _debug "EC key"
  422. EC_SIGN="1"
  423. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  424. _debug2 crv $crv
  425. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  426. pubi=$(_math $pubi + 1)
  427. _debug2 pubi $pubi
  428. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  429. pubj=$(_math $pubj + 1)
  430. _debug2 pubj $pubj
  431. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  432. _debug2 pubtext "$pubtext"
  433. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  434. xlen=$(_math $xlen / 4)
  435. _debug2 xlen $xlen
  436. xend=$(_math $xend + 1)
  437. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  438. _debug2 x $x
  439. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  440. _debug2 x64 $x64
  441. xend=$(_math $xend + 1)
  442. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  443. _debug2 y $y
  444. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  445. _debug2 y64 $y64
  446. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  447. _debug2 jwk "$jwk"
  448. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  449. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  450. else
  451. _err "Only RSA or EC key is supported."
  452. return 1
  453. fi
  454. _debug2 HEADER "$HEADER"
  455. }
  456. # body url [needbase64]
  457. _post() {
  458. body="$1"
  459. url="$2"
  460. needbase64="$3"
  461. if _exists "curl" ; then
  462. CURL="$CURL --dump-header $HTTP_HEADER "
  463. if [ "$needbase64" ] ; then
  464. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url | _base64)"
  465. else
  466. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url)"
  467. fi
  468. else
  469. if [ "$needbase64" ] ; then
  470. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
  471. else
  472. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER")"
  473. fi
  474. _sed_i "s/^ *//g" "$HTTP_HEADER"
  475. fi
  476. echo -n "$response"
  477. }
  478. # url getheader
  479. _get() {
  480. url="$1"
  481. onlyheader="$2"
  482. _debug url $url
  483. if _exists "curl" ; then
  484. if [ "$onlyheader" ] ; then
  485. $CURL -I -A "User-Agent: $USER_AGENT" $url
  486. else
  487. $CURL -A "User-Agent: $USER_AGENT" $url
  488. fi
  489. else
  490. _debug "WGET" "$WGET"
  491. if [ "$onlyheader" ] ; then
  492. eval $WGET --user-agent=\"$USER_AGENT\" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  493. else
  494. eval $WGET --user-agent=\"$USER_AGENT\" -O - $url
  495. fi
  496. fi
  497. ret=$?
  498. return $ret
  499. }
  500. # url payload needbase64 keyfile
  501. _send_signed_request() {
  502. url=$1
  503. payload=$2
  504. needbase64=$3
  505. keyfile=$4
  506. if [ -z "$keyfile" ] ; then
  507. keyfile="$ACCOUNT_KEY_PATH"
  508. fi
  509. _debug url $url
  510. _debug payload "$payload"
  511. if ! _calcjwk "$keyfile" ; then
  512. return 1
  513. fi
  514. payload64=$(echo -n $payload | _base64 | _urlencode)
  515. _debug2 payload64 $payload64
  516. nonceurl="$API/directory"
  517. nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
  518. _debug nonce "$nonce"
  519. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  520. _debug2 protected "$protected"
  521. protected64="$(printf "$protected" | _base64 | _urlencode)"
  522. _debug2 protected64 "$protected64"
  523. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  524. _debug2 sig "$sig"
  525. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  526. _debug2 body "$body"
  527. response="$(_post "$body" $url "$needbase64" )"
  528. responseHeaders="$(cat $HTTP_HEADER)"
  529. _debug2 responseHeaders "$responseHeaders"
  530. _debug2 response "$response"
  531. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  532. _debug code $code
  533. }
  534. #setopt "file" "opt" "=" "value" [";"]
  535. _setopt() {
  536. __conf="$1"
  537. __opt="$2"
  538. __sep="$3"
  539. __val="$4"
  540. __end="$5"
  541. if [ -z "$__opt" ] ; then
  542. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  543. return
  544. fi
  545. if [ ! -f "$__conf" ] ; then
  546. touch "$__conf"
  547. fi
  548. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  549. _debug2 OK
  550. if _contains "$__val" "&" ; then
  551. __val="$(echo $__val | sed 's/&/\\&/g')"
  552. fi
  553. text="$(cat $__conf)"
  554. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  555. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  556. if _contains "$__val" "&" ; then
  557. __val="$(echo $__val | sed 's/&/\\&/g')"
  558. fi
  559. text="$(cat $__conf)"
  560. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  561. else
  562. _debug2 APP
  563. echo "$__opt$__sep$__val$__end" >> "$__conf"
  564. fi
  565. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  566. }
  567. #_savedomainconf key value
  568. #save to domain.conf
  569. _savedomainconf() {
  570. key="$1"
  571. value="$2"
  572. if [ "$DOMAIN_CONF" ] ; then
  573. _setopt $DOMAIN_CONF "$key" "=" "$value"
  574. else
  575. _err "DOMAIN_CONF is empty, can not save $key=$value"
  576. fi
  577. }
  578. #_saveaccountconf key value
  579. _saveaccountconf() {
  580. key="$1"
  581. value="$2"
  582. if [ "$ACCOUNT_CONF_PATH" ] ; then
  583. _setopt $ACCOUNT_CONF_PATH "$key" "=" "\"$value\""
  584. else
  585. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  586. fi
  587. }
  588. _startserver() {
  589. content="$1"
  590. _debug "startserver: $$"
  591. nchelp="$(nc -h 2>&1)"
  592. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  593. _NC="nc -q 1 -l"
  594. else
  595. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  596. _NC="nc -c -l"
  597. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  598. _NC="nc -N -l"
  599. else
  600. _NC="nc -l"
  601. fi
  602. fi
  603. _debug "_NC" "$_NC"
  604. # while true ; do
  605. if [ "$DEBUG" ] ; then
  606. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort -vv ; then
  607. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort -vv ;
  608. fi
  609. else
  610. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  611. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  612. fi
  613. fi
  614. if [ "$?" != "0" ] ; then
  615. _err "nc listen error."
  616. exit 1
  617. fi
  618. # done
  619. }
  620. _stopserver(){
  621. pid="$1"
  622. _debug "pid" "$pid"
  623. if [ -z "$pid" ] ; then
  624. return
  625. fi
  626. if [ "$(ps | grep "$pid")" ] ; then
  627. _debug "Found proc process, kill it."
  628. kill -s 9 $pid > /dev/null
  629. fi
  630. for ncid in $(echo $(ps | grep nc) | cut -d " " -f 1) ; do
  631. _debug "kill $ncid"
  632. kill -s 9 $ncid > /dev/null
  633. done
  634. _get "http://localhost:$Le_HTTPPort" >/dev/null 2>&1
  635. }
  636. _initpath() {
  637. if [ -z "$LE_WORKING_DIR" ] ; then
  638. LE_WORKING_DIR=$HOME/.$PROJECT_NAME
  639. fi
  640. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  641. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  642. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  643. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  644. fi
  645. fi
  646. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  647. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  648. fi
  649. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  650. . "$ACCOUNT_CONF_PATH"
  651. fi
  652. if [ "$IN_CRON" ] ; then
  653. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  654. _USER_PATH_EXPORTED=1
  655. export PATH="$USER_PATH:$PATH"
  656. fi
  657. fi
  658. if [ -z "$API" ] ; then
  659. if [ -z "$STAGE" ] ; then
  660. API="$DEFAULT_CA"
  661. else
  662. API="$STAGE_CA"
  663. _info "Using stage api:$API"
  664. fi
  665. fi
  666. if [ -z "$ACME_DIR" ] ; then
  667. ACME_DIR="/home/.acme"
  668. fi
  669. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  670. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  671. fi
  672. if [ -z "$USER_AGENT" ] ; then
  673. USER_AGENT="$DEFAULT_USER_AGENT"
  674. fi
  675. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  676. WGET="wget -q"
  677. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  678. WGET="$WGET -d "
  679. fi
  680. dp="$LE_WORKING_DIR/curl.dump"
  681. CURL="curl -L --silent"
  682. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  683. CURL="$CURL -L --trace-ascii $dp "
  684. fi
  685. _DEFAULT_ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  686. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  687. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  688. fi
  689. domain="$1"
  690. if [ -z "$domain" ] ; then
  691. return 0
  692. fi
  693. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  694. if [ -z "$CERT_HOME" ] ; then
  695. CERT_HOME="$_DEFAULT_CERT_HOME"
  696. fi
  697. domainhome="$CERT_HOME/$domain"
  698. mkdir -p "$domainhome"
  699. if [ -z "$DOMAIN_PATH" ] ; then
  700. DOMAIN_PATH="$domainhome"
  701. fi
  702. if [ -z "$DOMAIN_CONF" ] ; then
  703. DOMAIN_CONF="$domainhome/$domain.conf"
  704. fi
  705. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  706. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  707. fi
  708. if [ -z "$CSR_PATH" ] ; then
  709. CSR_PATH="$domainhome/$domain.csr"
  710. fi
  711. if [ -z "$CERT_KEY_PATH" ] ; then
  712. CERT_KEY_PATH="$domainhome/$domain.key"
  713. fi
  714. if [ -z "$CERT_PATH" ] ; then
  715. CERT_PATH="$domainhome/$domain.cer"
  716. fi
  717. if [ -z "$CA_CERT_PATH" ] ; then
  718. CA_CERT_PATH="$domainhome/ca.cer"
  719. fi
  720. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  721. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  722. fi
  723. if [ -z "$CERT_PFX_PATH" ] ; then
  724. CERT_PFX_PATH="$domainhome/$domain.pfx"
  725. fi
  726. }
  727. _apachePath() {
  728. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  729. if _startswith "$httpdconfname" '/' ; then
  730. httpdconf="$httpdconfname"
  731. httpdconfname="$(basename $httpdconfname)"
  732. else
  733. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  734. httpdconf="$httpdroot/$httpdconfname"
  735. fi
  736. if [ ! -f $httpdconf ] ; then
  737. _err "Apache Config file not found" $httpdconf
  738. return 1
  739. fi
  740. return 0
  741. }
  742. _restoreApache() {
  743. if [ -z "$usingApache" ] ; then
  744. return 0
  745. fi
  746. _initpath
  747. if ! _apachePath ; then
  748. return 1
  749. fi
  750. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  751. _debug "No config file to restore."
  752. return 0
  753. fi
  754. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  755. _debug "Restored: $httpdconf."
  756. if ! apachectl -t ; then
  757. _err "Sorry, restore apache config error, please contact me."
  758. return 1;
  759. fi
  760. _debug "Restored successfully."
  761. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  762. return 0
  763. }
  764. _setApache() {
  765. _initpath
  766. if ! _apachePath ; then
  767. return 1
  768. fi
  769. #backup the conf
  770. _debug "Backup apache config file" $httpdconf
  771. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  772. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  773. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  774. _info "The backup file will be deleted on sucess, just forget it."
  775. #add alias
  776. apacheVer="$(apachectl -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  777. _debug "apacheVer" "$apacheVer"
  778. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  779. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  780. if [ "$apacheVer" ] && [ "$apacheMajer" -ge "2" ] && [ "$apacheMinor" -ge "4" ] ; then
  781. echo "
  782. Alias /.well-known/acme-challenge $ACME_DIR
  783. <Directory $ACME_DIR >
  784. Require all granted
  785. </Directory>
  786. " >> $httpdconf
  787. else
  788. echo "
  789. Alias /.well-known/acme-challenge $ACME_DIR
  790. <Directory $ACME_DIR >
  791. Order allow,deny
  792. Allow from all
  793. </Directory>
  794. " >> $httpdconf
  795. fi
  796. if ! apachectl -t ; then
  797. _err "Sorry, apache config error, please contact me."
  798. _restoreApache
  799. return 1;
  800. fi
  801. if [ ! -d "$ACME_DIR" ] ; then
  802. mkdir -p "$ACME_DIR"
  803. chmod 755 "$ACME_DIR"
  804. fi
  805. if ! apachectl graceful ; then
  806. _err "Sorry, apachectl graceful error, please contact me."
  807. _restoreApache
  808. return 1;
  809. fi
  810. usingApache="1"
  811. return 0
  812. }
  813. _clearup() {
  814. _stopserver $serverproc
  815. serverproc=""
  816. _restoreApache
  817. }
  818. # webroot removelevel tokenfile
  819. _clearupwebbroot() {
  820. __webroot="$1"
  821. if [ -z "$__webroot" ] ; then
  822. _debug "no webroot specified, skip"
  823. return 0
  824. fi
  825. if [ "$2" = '1' ] ; then
  826. _debug "remove $__webroot/.well-known"
  827. rm -rf "$__webroot/.well-known"
  828. elif [ "$2" = '2' ] ; then
  829. _debug "remove $__webroot/.well-known/acme-challenge"
  830. rm -rf "$__webroot/.well-known/acme-challenge"
  831. elif [ "$2" = '3' ] ; then
  832. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  833. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  834. else
  835. _info "Skip for removelevel:$2"
  836. fi
  837. return 0
  838. }
  839. issue() {
  840. if [ -z "$2" ] ; then
  841. echo "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  842. return 1
  843. fi
  844. Le_Webroot="$1"
  845. Le_Domain="$2"
  846. Le_Alt="$3"
  847. Le_Keylength="$4"
  848. Le_RealCertPath="$5"
  849. Le_RealKeyPath="$6"
  850. Le_RealCACertPath="$7"
  851. Le_ReloadCmd="$8"
  852. Le_RealFullChainPath="$9"
  853. #remove these later.
  854. if [ "$Le_Webroot" = "dns-cf" ] ; then
  855. Le_Webroot="dns_cf"
  856. fi
  857. if [ "$Le_Webroot" = "dns-dp" ] ; then
  858. Le_Webroot="dns_dp"
  859. fi
  860. if [ "$Le_Webroot" = "dns-cx" ] ; then
  861. Le_Webroot="dns_cx"
  862. fi
  863. _initpath $Le_Domain
  864. if [ -f "$DOMAIN_CONF" ] ; then
  865. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  866. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  867. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  868. return 2
  869. fi
  870. fi
  871. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  872. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  873. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  874. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  875. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  876. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  877. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  878. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  879. _setopt "$DOMAIN_CONF" "Le_RealFullChainPath" "=" "\"$Le_RealFullChainPath\""
  880. if [ "$Le_Alt" = "no" ] ; then
  881. Le_Alt=""
  882. fi
  883. if [ "$Le_Keylength" = "no" ] ; then
  884. Le_Keylength=""
  885. fi
  886. if [ "$Le_RealCertPath" = "no" ] ; then
  887. Le_RealCertPath=""
  888. fi
  889. if [ "$Le_RealKeyPath" = "no" ] ; then
  890. Le_RealKeyPath=""
  891. fi
  892. if [ "$Le_RealCACertPath" = "no" ] ; then
  893. Le_RealCACertPath=""
  894. fi
  895. if [ "$Le_ReloadCmd" = "no" ] ; then
  896. Le_ReloadCmd=""
  897. fi
  898. if [ "$Le_RealFullChainPath" = "no" ] ; then
  899. Le_RealFullChainPath=""
  900. fi
  901. if _contains "$Le_Webroot" "no" ; then
  902. _info "Standalone mode."
  903. if ! _exists "nc" ; then
  904. _err "Please install netcat(nc) tools first."
  905. return 1
  906. fi
  907. if [ -z "$Le_HTTPPort" ] ; then
  908. Le_HTTPPort=80
  909. fi
  910. _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
  911. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  912. if [ "$netprc" ] ; then
  913. _err "$netprc"
  914. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  915. _err "Please stop it first"
  916. return 1
  917. fi
  918. fi
  919. if _contains "$Le_Webroot" "apache" ; then
  920. if ! _setApache ; then
  921. _err "set up apache error. Report error to me."
  922. return 1
  923. fi
  924. else
  925. usingApache=""
  926. fi
  927. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  928. if ! createAccountKey $Le_Domain $Le_Keylength ; then
  929. _err "Create account key error."
  930. if [ "$usingApache" ] ; then
  931. _restoreApache
  932. fi
  933. return 1
  934. fi
  935. fi
  936. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  937. if [ "$usingApache" ] ; then
  938. _restoreApache
  939. fi
  940. return 1
  941. fi
  942. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  943. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  944. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  945. accountkeyhash="$(echo $accountkeyhash$API | _digest "sha256" )"
  946. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  947. _info "Registering account"
  948. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  949. if [ "$ACCOUNT_EMAIL" ] ; then
  950. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  951. fi
  952. _send_signed_request "$API/acme/new-reg" "$regjson"
  953. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  954. _info "Registered"
  955. echo $response > $LE_WORKING_DIR/account.json
  956. elif [ "$code" = '409' ] ; then
  957. _info "Already registered"
  958. else
  959. _err "Register account Error: $response"
  960. _clearup
  961. return 1
  962. fi
  963. ACCOUNT_KEY_HASH="$accountkeyhash"
  964. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  965. else
  966. _info "Skip register account key"
  967. fi
  968. if [ ! -f "$CERT_KEY_PATH" ] ; then
  969. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  970. _err "Create domain key error."
  971. _clearup
  972. return 1
  973. fi
  974. fi
  975. if ! createCSR $Le_Domain $Le_Alt ; then
  976. _err "Create CSR error."
  977. _clearup
  978. return 1
  979. fi
  980. vlist="$Le_Vlist"
  981. # verify each domain
  982. _info "Verify each domain"
  983. sep='#'
  984. if [ -z "$vlist" ] ; then
  985. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  986. _index=1
  987. _currentRoot=""
  988. for d in $alldomains
  989. do
  990. _info "Getting webroot for domain" $d
  991. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  992. _debug _w "$_w"
  993. if [ "$_w" ] ; then
  994. _currentRoot="$_w"
  995. fi
  996. _debug "_currentRoot" "$_currentRoot"
  997. _index=$(_math $_index + 1)
  998. vtype="$VTYPE_HTTP"
  999. if _startswith "$_currentRoot" "dns" ; then
  1000. vtype="$VTYPE_DNS"
  1001. fi
  1002. _info "Getting token for domain" $d
  1003. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  1004. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  1005. _err "new-authz error: $response"
  1006. _clearup
  1007. return 1
  1008. fi
  1009. entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  1010. _debug entry "$entry"
  1011. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1012. _debug token $token
  1013. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1014. _debug uri $uri
  1015. keyauthorization="$token.$thumbprint"
  1016. _debug keyauthorization "$keyauthorization"
  1017. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1018. _debug dvlist "$dvlist"
  1019. vlist="$vlist$dvlist,"
  1020. done
  1021. #add entry
  1022. dnsadded=""
  1023. ventries=$(echo "$vlist" | tr ',' ' ' )
  1024. for ventry in $ventries
  1025. do
  1026. d=$(echo $ventry | cut -d $sep -f 1)
  1027. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1028. vtype=$(echo $ventry | cut -d $sep -f 4)
  1029. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1030. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1031. dnsadded='0'
  1032. txtdomain="_acme-challenge.$d"
  1033. _debug txtdomain "$txtdomain"
  1034. txt="$(echo -e -n $keyauthorization | _digest "sha256" | _urlencode)"
  1035. _debug txt "$txt"
  1036. #dns
  1037. #1. check use api
  1038. d_api=""
  1039. if [ -f "$LE_WORKING_DIR/$d/$_currentRoot" ] ; then
  1040. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  1041. elif [ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ] ; then
  1042. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  1043. elif [ -f "$LE_WORKING_DIR/$_currentRoot" ] ; then
  1044. d_api="$LE_WORKING_DIR/$_currentRoot"
  1045. elif [ -f "$LE_WORKING_DIR/$_currentRoot.sh" ] ; then
  1046. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  1047. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ] ; then
  1048. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  1049. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ] ; then
  1050. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  1051. fi
  1052. _debug d_api "$d_api"
  1053. if [ "$d_api" ] ; then
  1054. _info "Found domain api file: $d_api"
  1055. else
  1056. _err "Add the following TXT record:"
  1057. _err "Domain: $txtdomain"
  1058. _err "TXT value: $txt"
  1059. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1060. _err "so the resulting subdomain will be: $txtdomain"
  1061. continue
  1062. fi
  1063. (
  1064. if ! . $d_api ; then
  1065. _err "Load file $d_api error. Please check your api file and try again."
  1066. return 1
  1067. fi
  1068. addcommand="${_currentRoot}_add"
  1069. if ! _exists $addcommand ; then
  1070. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1071. return 1
  1072. fi
  1073. if ! $addcommand $txtdomain $txt ; then
  1074. _err "Error add txt for domain:$txtdomain"
  1075. return 1
  1076. fi
  1077. )
  1078. if [ "$?" != "0" ] ; then
  1079. _clearup
  1080. return 1
  1081. fi
  1082. dnsadded='1'
  1083. fi
  1084. done
  1085. if [ "$dnsadded" = '0' ] ; then
  1086. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  1087. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1088. _err "Please add the TXT records to the domains, and retry again."
  1089. _clearup
  1090. return 1
  1091. fi
  1092. fi
  1093. if [ "$dnsadded" = '1' ] ; then
  1094. _info "Sleep 60 seconds for the txt records to take effect"
  1095. sleep 60
  1096. fi
  1097. _debug "ok, let's start to verify"
  1098. ventries=$(echo "$vlist" | tr ',' ' ' )
  1099. for ventry in $ventries
  1100. do
  1101. d=$(echo $ventry | cut -d $sep -f 1)
  1102. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1103. uri=$(echo $ventry | cut -d $sep -f 3)
  1104. vtype=$(echo $ventry | cut -d $sep -f 4)
  1105. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1106. _info "Verifying:$d"
  1107. _debug "d" "$d"
  1108. _debug "keyauthorization" "$keyauthorization"
  1109. _debug "uri" "$uri"
  1110. removelevel=""
  1111. token=""
  1112. _debug "_currentRoot" "$_currentRoot"
  1113. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1114. if [ "$_currentRoot" = "no" ] ; then
  1115. _info "Standalone mode server"
  1116. _startserver "$keyauthorization" &
  1117. if [ "$?" != "0" ] ; then
  1118. _clearup
  1119. return 1
  1120. fi
  1121. serverproc="$!"
  1122. sleep 2
  1123. _debug serverproc $serverproc
  1124. else
  1125. if [ "$_currentRoot" = "apache" ] ; then
  1126. wellknown_path="$ACME_DIR"
  1127. else
  1128. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1129. if [ ! -d "$_currentRoot/.well-known" ] ; then
  1130. removelevel='1'
  1131. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  1132. removelevel='2'
  1133. else
  1134. removelevel='3'
  1135. fi
  1136. fi
  1137. _debug wellknown_path "$wellknown_path"
  1138. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  1139. _debug "writing token:$token to $wellknown_path/$token"
  1140. mkdir -p "$wellknown_path"
  1141. echo -n "$keyauthorization" > "$wellknown_path/$token"
  1142. if [ ! "$usingApache" ] ; then
  1143. webroot_owner=$(_stat $_currentRoot)
  1144. _debug "Changing owner/group of .well-known to $webroot_owner"
  1145. chown -R $webroot_owner "$_currentRoot/.well-known"
  1146. fi
  1147. fi
  1148. fi
  1149. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  1150. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  1151. _err "$d:Challenge error: $response"
  1152. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1153. _clearup
  1154. return 1
  1155. fi
  1156. waittimes=0
  1157. if [ -z "$MAX_RETRY_TIMES" ] ; then
  1158. MAX_RETRY_TIMES=30
  1159. fi
  1160. while [ "1" ] ; do
  1161. waittimes=$(_math $waittimes + 1)
  1162. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  1163. _err "$d:Timeout"
  1164. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1165. _clearup
  1166. return 1
  1167. fi
  1168. _debug "sleep 5 secs to verify"
  1169. sleep 5
  1170. _debug "checking"
  1171. response="$(_get $uri)"
  1172. if [ "$?" != "0" ] ; then
  1173. _err "$d:Verify error:$response"
  1174. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1175. _clearup
  1176. return 1
  1177. fi
  1178. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1179. if [ "$status" = "valid" ] ; then
  1180. _info "Success"
  1181. _stopserver $serverproc
  1182. serverproc=""
  1183. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1184. break;
  1185. fi
  1186. if [ "$status" = "invalid" ] ; then
  1187. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  1188. _err "$d:Verify error:$error"
  1189. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1190. _clearup
  1191. return 1;
  1192. fi
  1193. if [ "$status" = "pending" ] ; then
  1194. _info "Pending"
  1195. else
  1196. _err "$d:Verify error:$response"
  1197. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1198. _clearup
  1199. return 1
  1200. fi
  1201. done
  1202. done
  1203. _clearup
  1204. _info "Verify finished, start to sign."
  1205. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1206. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1207. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1208. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  1209. if [ "$Le_LinkCert" ] ; then
  1210. echo "$BEGIN_CERT" > "$CERT_PATH"
  1211. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1212. echo "$END_CERT" >> "$CERT_PATH"
  1213. _info "Cert success."
  1214. cat "$CERT_PATH"
  1215. _info "Your cert is in $CERT_PATH"
  1216. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1217. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  1218. USER_PATH="$PATH"
  1219. _saveaccountconf "USER_PATH" "$USER_PATH"
  1220. fi
  1221. fi
  1222. if [ -z "$Le_LinkCert" ] ; then
  1223. response="$(echo $response | _dbase64 "multiline" )"
  1224. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1225. return 1
  1226. fi
  1227. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  1228. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1229. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  1230. if [ "$Le_LinkIssuer" ] ; then
  1231. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1232. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1233. echo "$END_CERT" >> "$CA_CERT_PATH"
  1234. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1235. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1236. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1237. fi
  1238. Le_CertCreateTime=$(date -u "+%s")
  1239. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  1240. Le_CertCreateTimeStr=$(date -u )
  1241. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  1242. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "80" ] ; then
  1243. Le_RenewalDays=80
  1244. fi
  1245. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  1246. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  1247. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  1248. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1249. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  1250. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1251. }
  1252. renew() {
  1253. Le_Domain="$1"
  1254. if [ -z "$Le_Domain" ] ; then
  1255. _err "Usage: $PROJECT_ENTRY --renew -d domain.com"
  1256. return 1
  1257. fi
  1258. _initpath $Le_Domain
  1259. if [ ! -f "$DOMAIN_CONF" ] ; then
  1260. _info "$Le_Domain is not a issued domain, skip."
  1261. return 0;
  1262. fi
  1263. . "$DOMAIN_CONF"
  1264. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1265. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1266. return 2
  1267. fi
  1268. IS_RENEW="1"
  1269. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1270. local res=$?
  1271. IS_RENEW=""
  1272. return $res
  1273. }
  1274. renewAll() {
  1275. _initpath
  1276. _info "renewAll"
  1277. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1278. d=$(echo $d | cut -d '/' -f 1)
  1279. _info "renew $d"
  1280. Le_LinkCert=""
  1281. Le_Domain=""
  1282. Le_Alt="no"
  1283. Le_Webroot=""
  1284. Le_Keylength=""
  1285. Le_LinkIssuer=""
  1286. Le_CertCreateTime=""
  1287. Le_CertCreateTimeStr=""
  1288. Le_RenewalDays=""
  1289. Le_NextRenewTime=""
  1290. Le_NextRenewTimeStr=""
  1291. Le_RealCertPath=""
  1292. Le_RealKeyPath=""
  1293. Le_RealCACertPath=""
  1294. Le_ReloadCmd=""
  1295. Le_RealFullChainPath=""
  1296. DOMAIN_PATH=""
  1297. DOMAIN_CONF=""
  1298. DOMAIN_SSL_CONF=""
  1299. CSR_PATH=""
  1300. CERT_KEY_PATH=""
  1301. CERT_PATH=""
  1302. CA_CERT_PATH=""
  1303. CERT_PFX_PATH=""
  1304. CERT_FULLCHAIN_PATH=""
  1305. ACCOUNT_KEY_PATH=""
  1306. wellknown_path=""
  1307. renew "$d"
  1308. done
  1309. }
  1310. installcert() {
  1311. Le_Domain="$1"
  1312. if [ -z "$Le_Domain" ] ; then
  1313. echo "Usage: $PROJECT_ENTRY --installcert -d domain.com [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  1314. return 1
  1315. fi
  1316. Le_RealCertPath="$2"
  1317. Le_RealKeyPath="$3"
  1318. Le_RealCACertPath="$4"
  1319. Le_ReloadCmd="$5"
  1320. Le_RealFullChainPath="$6"
  1321. _initpath $Le_Domain
  1322. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  1323. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  1324. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  1325. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  1326. _setopt "$DOMAIN_CONF" "Le_RealFullChainPath" "=" "\"$Le_RealFullChainPath\""
  1327. if [ "$Le_RealCertPath" ] ; then
  1328. if [ -f "$Le_RealCertPath" ] ; then
  1329. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  1330. fi
  1331. cat "$CERT_PATH" > "$Le_RealCertPath"
  1332. fi
  1333. if [ "$Le_RealCACertPath" ] ; then
  1334. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  1335. echo "" >> "$Le_RealCACertPath"
  1336. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1337. else
  1338. if [ -f "$Le_RealCACertPath" ] ; then
  1339. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1340. fi
  1341. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1342. fi
  1343. fi
  1344. if [ "$Le_RealKeyPath" ] ; then
  1345. if [ -f "$Le_RealKeyPath" ] ; then
  1346. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1347. fi
  1348. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1349. fi
  1350. if [ "$Le_RealFullChainPath" ] ; then
  1351. if [ -f "$Le_RealFullChainPath" ] ; then
  1352. cp -p "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  1353. fi
  1354. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  1355. fi
  1356. if [ "$Le_ReloadCmd" ] ; then
  1357. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1358. (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
  1359. fi
  1360. }
  1361. installcronjob() {
  1362. _initpath
  1363. if ! _exists "crontab" ; then
  1364. _err "crontab doesn't exist, so, we can not install cron jobs."
  1365. _err "All your certs will not be renewed automatically."
  1366. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  1367. return 1
  1368. fi
  1369. _info "Installing cron job"
  1370. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  1371. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  1372. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  1373. else
  1374. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  1375. return 1
  1376. fi
  1377. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  1378. fi
  1379. if [ "$?" != "0" ] ; then
  1380. _err "Install cron job failed. You need to manually renew your certs."
  1381. _err "Or you can add cronjob by yourself:"
  1382. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  1383. return 1
  1384. fi
  1385. }
  1386. uninstallcronjob() {
  1387. if ! _exists "crontab" ; then
  1388. return
  1389. fi
  1390. _info "Removing cron job"
  1391. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  1392. if [ "$cr" ] ; then
  1393. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  1394. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  1395. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1396. fi
  1397. _initpath
  1398. }
  1399. revoke() {
  1400. Le_Domain="$1"
  1401. if [ -z "$Le_Domain" ] ; then
  1402. echo "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  1403. return 1
  1404. fi
  1405. _initpath $Le_Domain
  1406. if [ ! -f "$DOMAIN_CONF" ] ; then
  1407. _err "$Le_Domain is not a issued domain, skip."
  1408. return 1;
  1409. fi
  1410. if [ ! -f "$CERT_PATH" ] ; then
  1411. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1412. return 1
  1413. fi
  1414. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1415. if [ -z "$cert" ] ; then
  1416. _err "Cert for $Le_Domain is empty found, skip."
  1417. return 1
  1418. fi
  1419. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1420. uri="$API/acme/revoke-cert"
  1421. _info "Try domain key first."
  1422. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1423. if [ -z "$response" ] ; then
  1424. _info "Revoke success."
  1425. rm -f $CERT_PATH
  1426. return 0
  1427. else
  1428. _err "Revoke error by domain key."
  1429. _err "$resource"
  1430. fi
  1431. fi
  1432. _info "Then try account key."
  1433. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1434. if [ -z "$response" ] ; then
  1435. _info "Revoke success."
  1436. rm -f $CERT_PATH
  1437. return 0
  1438. else
  1439. _err "Revoke error."
  1440. _debug "$resource"
  1441. fi
  1442. fi
  1443. return 1
  1444. }
  1445. # Detect profile file if not specified as environment variable
  1446. _detect_profile() {
  1447. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  1448. echo "$PROFILE"
  1449. return
  1450. fi
  1451. local DETECTED_PROFILE
  1452. DETECTED_PROFILE=''
  1453. local SHELLTYPE
  1454. SHELLTYPE="$(basename "/$SHELL")"
  1455. if [ "$SHELLTYPE" = "bash" ] ; then
  1456. if [ -f "$HOME/.bashrc" ] ; then
  1457. DETECTED_PROFILE="$HOME/.bashrc"
  1458. elif [ -f "$HOME/.bash_profile" ] ; then
  1459. DETECTED_PROFILE="$HOME/.bash_profile"
  1460. fi
  1461. elif [ "$SHELLTYPE" = "zsh" ] ; then
  1462. DETECTED_PROFILE="$HOME/.zshrc"
  1463. fi
  1464. if [ -z "$DETECTED_PROFILE" ] ; then
  1465. if [ -f "$HOME/.profile" ] ; then
  1466. DETECTED_PROFILE="$HOME/.profile"
  1467. elif [ -f "$HOME/.bashrc" ] ; then
  1468. DETECTED_PROFILE="$HOME/.bashrc"
  1469. elif [ -f "$HOME/.bash_profile" ] ; then
  1470. DETECTED_PROFILE="$HOME/.bash_profile"
  1471. elif [ -f "$HOME/.zshrc" ] ; then
  1472. DETECTED_PROFILE="$HOME/.zshrc"
  1473. fi
  1474. fi
  1475. if [ ! -z "$DETECTED_PROFILE" ] ; then
  1476. echo "$DETECTED_PROFILE"
  1477. fi
  1478. }
  1479. _initconf() {
  1480. _initpath
  1481. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1482. echo "#ACCOUNT_CONF_PATH=xxxx
  1483. #Account configurations:
  1484. #Here are the supported macros, uncomment them to make them take effect.
  1485. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1486. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1487. #CERT_HOME=\"/path/to/cert/home\"
  1488. #STAGE=1 # Use the staging api
  1489. #FORCE=1 # Force to issue cert
  1490. #DEBUG=1 # Debug mode
  1491. #ACCOUNT_KEY_HASH=account key hash
  1492. USER_AGENT=\"$USER_AGENT\"
  1493. #USER_PATH=""
  1494. #dns api
  1495. #######################
  1496. #Cloudflare:
  1497. #api key
  1498. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1499. #account email
  1500. #CF_Email=\"xxxx@sss.com\"
  1501. #######################
  1502. #Dnspod.cn:
  1503. #api key id
  1504. #DP_Id=\"1234\"
  1505. #api key
  1506. #DP_Key=\"sADDsdasdgdsf\"
  1507. #######################
  1508. #Cloudxns.com:
  1509. #CX_Key=\"1234\"
  1510. #
  1511. #CX_Secret=\"sADDsdasdgdsf\"
  1512. " > $ACCOUNT_CONF_PATH
  1513. fi
  1514. }
  1515. _precheck() {
  1516. if ! _exists "curl" && ! _exists "wget"; then
  1517. _err "Please install curl or wget first, we need to access http resources."
  1518. return 1
  1519. fi
  1520. if ! _exists "crontab" ; then
  1521. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1522. _err "We need to set cron job to renew the certs automatically."
  1523. _err "Otherwise, your certs will not be able to be renewed automatically."
  1524. if [ -z "$FORCE" ] ; then
  1525. _err "Please add '--force' and try install again to go without crontab."
  1526. _err "./$PROJECT_ENTRY --install --force"
  1527. return 1
  1528. fi
  1529. fi
  1530. if ! _exists "openssl" ; then
  1531. _err "Please install openssl first."
  1532. _err "We need openssl to generate keys."
  1533. return 1
  1534. fi
  1535. if ! _exists "nc" ; then
  1536. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1537. _err "We use nc for standalone server if you use standalone mode."
  1538. _err "If you don't use standalone mode, just ignore this warning."
  1539. fi
  1540. return 0
  1541. }
  1542. install() {
  1543. if ! _initpath ; then
  1544. _err "Install failed."
  1545. return 1
  1546. fi
  1547. if ! _precheck ; then
  1548. _err "Pre-check failed, can not install."
  1549. return 1
  1550. fi
  1551. #convert from le
  1552. if [ -d "$HOME/.le" ] ; then
  1553. for envfile in "le.env" "le.sh.env"
  1554. do
  1555. if [ -f "$HOME/.le/$envfile" ] ; then
  1556. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  1557. _upgrading="1"
  1558. _info "You are upgrading from le.sh"
  1559. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  1560. mv "$HOME/.le" "$LE_WORKING_DIR"
  1561. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1562. break;
  1563. fi
  1564. fi
  1565. done
  1566. fi
  1567. _info "Installing to $LE_WORKING_DIR"
  1568. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1569. _err "Can not craete working dir: $LE_WORKING_DIR"
  1570. return 1
  1571. fi
  1572. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  1573. if [ "$?" != "0" ] ; then
  1574. _err "Install failed, can not copy $PROJECT_ENTRY"
  1575. return 1
  1576. fi
  1577. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  1578. _profile="$(_detect_profile)"
  1579. if [ "$_profile" ] ; then
  1580. _debug "Found profile: $_profile"
  1581. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1582. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  1583. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  1584. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  1585. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  1586. fi
  1587. _setopt "$_envfile" "LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  1588. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1589. echo "" >> "$_profile"
  1590. _setopt "$_profile" ". \"$LE_WORKING_DIR/$PROJECT_NAME.env\""
  1591. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  1592. else
  1593. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  1594. fi
  1595. if [ -d "dnsapi" ] ; then
  1596. mkdir -p $LE_WORKING_DIR/dnsapi
  1597. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1598. fi
  1599. #to keep compatible mv the .acc file to .key file
  1600. if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
  1601. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1602. fi
  1603. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1604. _initconf
  1605. fi
  1606. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  1607. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  1608. fi
  1609. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  1610. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  1611. fi
  1612. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  1613. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  1614. fi
  1615. installcronjob
  1616. _info OK
  1617. }
  1618. uninstall() {
  1619. uninstallcronjob
  1620. _initpath
  1621. _profile="$(_detect_profile)"
  1622. if [ "$_profile" ] ; then
  1623. text="$(cat $_profile)"
  1624. echo "$text" | sed "s|^source.*$PROJECT_NAME.env.*$||" > "$_profile"
  1625. fi
  1626. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  1627. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1628. }
  1629. cron() {
  1630. IN_CRON=1
  1631. renewAll
  1632. IN_CRON=""
  1633. }
  1634. version() {
  1635. echo "$PROJECT"
  1636. echo "v$VER"
  1637. }
  1638. showhelp() {
  1639. version
  1640. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  1641. Commands:
  1642. --help, -h Show this help message.
  1643. --version, -v Show version info.
  1644. --install Install $PROJECT_NAME to your system.
  1645. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  1646. --issue Issue a cert.
  1647. --installcert Install the issued cert to apache/nginx or any other server.
  1648. --renew, -r Renew a cert.
  1649. --renewAll Renew all the certs
  1650. --revoke Revoke a cert.
  1651. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1652. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  1653. --cron Run cron job to renew all the certs.
  1654. --toPkcs Export the certificate and key to a pfx file.
  1655. --createAccountKey, -cak Create an account private key, professional use.
  1656. --createDomainKey, -cdk Create an domain private key, professional use.
  1657. --createCSR, -ccsr Create CSR , professional use.
  1658. Parameters:
  1659. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  1660. --force, -f Used to force to install or force to renew a cert immediately.
  1661. --staging, --test Use staging server, just for test.
  1662. --debug Output debug info.
  1663. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  1664. --standalone Use standalone mode.
  1665. --apache Use apache mode.
  1666. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  1667. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  1668. --accountkeylength, -ak [2048] Specifies the account key length.
  1669. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  1670. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  1671. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  1672. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  1673. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  1674. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  1675. --accountconf Specifies a customized account config file.
  1676. --home Specifies the home dir for $PROJECT_NAME .
  1677. --certhome Specifies the home dir to save all the certs.
  1678. --useragent Specifies the user agent string. it will be saved for future use too.
  1679. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  1680. --accountkey Specifies the account key path, Only valid for the '--install' command.
  1681. --days Specifies the days to renew the cert when using '--issue' command. The max value is 80 days.
  1682. "
  1683. }
  1684. _installOnline() {
  1685. _info "Installing from online archive."
  1686. if [ ! "$BRANCH" ] ; then
  1687. BRANCH="master"
  1688. fi
  1689. _initpath
  1690. target="$PROJECT/archive/$BRANCH.tar.gz"
  1691. _info "Downloading $target"
  1692. localname="$BRANCH.tar.gz"
  1693. if ! _get "$target" > $localname ; then
  1694. _debug "Download error."
  1695. return 1
  1696. fi
  1697. _info "Extracting $localname"
  1698. tar xzf $localname
  1699. cd "$PROJECT_NAME-$BRANCH"
  1700. chmod +x $PROJECT_ENTRY
  1701. if ./$PROJECT_ENTRY install ; then
  1702. _info "Install success!"
  1703. fi
  1704. cd ..
  1705. rm -rf "$PROJECT_NAME-$BRANCH"
  1706. rm -f "$localname"
  1707. }
  1708. _process() {
  1709. _CMD=""
  1710. _domain=""
  1711. _altdomains="no"
  1712. _webroot=""
  1713. _keylength="no"
  1714. _accountkeylength="no"
  1715. _certpath="no"
  1716. _keypath="no"
  1717. _capath="no"
  1718. _fullchainpath="no"
  1719. _reloadcmd="no"
  1720. _password=""
  1721. _accountconf=""
  1722. _useragent=""
  1723. _accountemail=""
  1724. _accountkey=""
  1725. _certhome=""
  1726. while [ ${#} -gt 0 ] ; do
  1727. case "${1}" in
  1728. --help|-h)
  1729. showhelp
  1730. return
  1731. ;;
  1732. --version|-v)
  1733. version
  1734. return
  1735. ;;
  1736. --install)
  1737. _CMD="install"
  1738. ;;
  1739. --uninstall)
  1740. _CMD="uninstall"
  1741. ;;
  1742. --issue)
  1743. _CMD="issue"
  1744. ;;
  1745. --installcert|-i)
  1746. _CMD="installcert"
  1747. ;;
  1748. --renew|-r)
  1749. _CMD="renew"
  1750. ;;
  1751. --renewAll|-renewall)
  1752. _CMD="renewAll"
  1753. ;;
  1754. --revoke)
  1755. _CMD="revoke"
  1756. ;;
  1757. --installcronjob)
  1758. _CMD="installcronjob"
  1759. ;;
  1760. --uninstallcronjob)
  1761. _CMD="uninstallcronjob"
  1762. ;;
  1763. --cron)
  1764. _CMD="cron"
  1765. ;;
  1766. --toPkcs)
  1767. _CMD="toPkcs"
  1768. ;;
  1769. --createAccountKey|--createaccountkey|-cak)
  1770. _CMD="createAccountKey"
  1771. ;;
  1772. --createDomainKey|--createdomainkey|-cdk)
  1773. _CMD="createDomainKey"
  1774. ;;
  1775. --createCSR|--createcsr|-ccr)
  1776. _CMD="createCSR"
  1777. ;;
  1778. --domain|-d)
  1779. _dvalue="$2"
  1780. if [ -z "$_dvalue" ] || _startswith "$_dvalue" "-" ; then
  1781. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  1782. return 1
  1783. fi
  1784. if [ -z "$_domain" ] ; then
  1785. _domain="$_dvalue"
  1786. else
  1787. if [ "$_altdomains" = "no" ] ; then
  1788. _altdomains="$_dvalue"
  1789. else
  1790. _altdomains="$_altdomains,$_dvalue"
  1791. fi
  1792. fi
  1793. shift
  1794. ;;
  1795. --force|-f)
  1796. FORCE="1"
  1797. ;;
  1798. --staging|--test)
  1799. STAGE="1"
  1800. ;;
  1801. --debug)
  1802. if [ -z "$2" ] || _startswith "$2" "-" ; then
  1803. DEBUG="1"
  1804. else
  1805. DEBUG="$2"
  1806. shift
  1807. fi
  1808. ;;
  1809. --webroot|-w)
  1810. wvalue="$2"
  1811. if [ -z "$_webroot" ] ; then
  1812. _webroot="$wvalue"
  1813. else
  1814. _webroot="$_webroot,$wvalue"
  1815. fi
  1816. shift
  1817. ;;
  1818. --standalone)
  1819. wvalue="no"
  1820. if [ -z "$_webroot" ] ; then
  1821. _webroot="$wvalue"
  1822. else
  1823. _webroot="$_webroot,$wvalue"
  1824. fi
  1825. ;;
  1826. --apache)
  1827. wvalue="apache"
  1828. if [ -z "$_webroot" ] ; then
  1829. _webroot="$wvalue"
  1830. else
  1831. _webroot="$_webroot,$wvalue"
  1832. fi
  1833. ;;
  1834. --dns)
  1835. wvalue="dns"
  1836. if ! _startswith "$2" "-" ; then
  1837. wvalue="$2"
  1838. shift
  1839. fi
  1840. if [ -z "$_webroot" ] ; then
  1841. _webroot="$wvalue"
  1842. else
  1843. _webroot="$_webroot,$wvalue"
  1844. fi
  1845. ;;
  1846. --keylength|-k)
  1847. _keylength="$2"
  1848. accountkeylength="$2"
  1849. shift
  1850. ;;
  1851. --accountkeylength|-ak)
  1852. accountkeylength="$2"
  1853. shift
  1854. ;;
  1855. --certpath)
  1856. _certpath="$2"
  1857. shift
  1858. ;;
  1859. --keypath)
  1860. _keypath="$2"
  1861. shift
  1862. ;;
  1863. --capath)
  1864. _capath="$2"
  1865. shift
  1866. ;;
  1867. --fullchainpath)
  1868. _fullchainpath="$2"
  1869. shift
  1870. ;;
  1871. --reloadcmd|--reloadCmd)
  1872. _reloadcmd="$2"
  1873. shift
  1874. ;;
  1875. --password)
  1876. _password="$2"
  1877. shift
  1878. ;;
  1879. --accountconf)
  1880. _accountconf="$2"
  1881. ACCOUNT_CONF_PATH="$_accountconf"
  1882. shift
  1883. ;;
  1884. --home)
  1885. LE_WORKING_DIR="$2"
  1886. shift
  1887. ;;
  1888. --certhome)
  1889. _certhome="$2"
  1890. CERT_HOME="$_certhome"
  1891. shift
  1892. ;;
  1893. --useragent)
  1894. _useragent="$2"
  1895. USER_AGENT="$_useragent"
  1896. shift
  1897. ;;
  1898. --accountemail )
  1899. _accountemail="$2"
  1900. ACCOUNT_EMAIL="$_accountemail"
  1901. shift
  1902. ;;
  1903. --accountkey )
  1904. _accountkey="$2"
  1905. ACCOUNT_KEY_PATH="$_accountkey"
  1906. shift
  1907. ;;
  1908. --days )
  1909. _days="$2"
  1910. Le_RenewalDays="$_days"
  1911. shift
  1912. ;;
  1913. *)
  1914. _err "Unknown parameter : $1"
  1915. return 1
  1916. ;;
  1917. esac
  1918. shift 1
  1919. done
  1920. case "${_CMD}" in
  1921. install) install ;;
  1922. uninstall) uninstall ;;
  1923. issue)
  1924. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1925. ;;
  1926. installcert)
  1927. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1928. ;;
  1929. renew)
  1930. renew "$_domain"
  1931. ;;
  1932. renewAll)
  1933. renewAll
  1934. ;;
  1935. revoke)
  1936. revoke "$_domain"
  1937. ;;
  1938. installcronjob) installcronjob ;;
  1939. uninstallcronjob) uninstallcronjob ;;
  1940. cron) cron ;;
  1941. toPkcs)
  1942. toPkcs "$_domain" "$_password"
  1943. ;;
  1944. createAccountKey)
  1945. createAccountKey "$_domain" "$_accountkeylength"
  1946. ;;
  1947. createDomainKey)
  1948. createDomainKey "$_domain" "$_keylength"
  1949. ;;
  1950. createCSR)
  1951. createCSR "$_domain" "$_altdomains"
  1952. ;;
  1953. *)
  1954. _err "Invalid command: $_CMD"
  1955. showhelp;
  1956. return 1
  1957. ;;
  1958. esac
  1959. if [ "$_useragent" ] ; then
  1960. _saveaccountconf "USER_AGENT" "$_useragent"
  1961. fi
  1962. if [ "$_accountemail" ] ; then
  1963. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  1964. fi
  1965. }
  1966. if [ "$INSTALLONLINE" ] ; then
  1967. INSTALLONLINE=""
  1968. _installOnline $BRANCH
  1969. exit
  1970. fi
  1971. if [ -z "$1" ] ; then
  1972. showhelp
  1973. else
  1974. if echo "$1" | grep "^-" >/dev/null 2>&1 ; then
  1975. _process "$@"
  1976. else
  1977. "$@"
  1978. fi
  1979. fi